using System;
using UnityEngine;

namespace KaoticSSB.Players
{
	public class BotBase : PlayerBase
	{
		public float MissDistance = 5.0f;

		public BotBase ()
		{
		}

		public override void Update ()
		{
			base.Update ();
			//CPU logic
			if(!Dead)
			{
				CPU_Update();
			}
		}

		public override void FixedUpdate ()
		{
			base.FixedUpdate ();
			float randomNum = UnityEngine.Random.Range(0.0f, 100.0f);
			if(randomNum >= 95.0f)
			{
				mShouldThrow = true;
			}
		}

		public override void Init ()
		{
			base.Init ();
			mShouldThrow = false;
		}

		/**
		 * This is a very basic ai that moves towards the player and throws if it thinks it should throw
		 */
		private void CPU_Update()
		{
			if(mTarget == null || mTarget.Dead)
			{
				mTarget = GetNewTarget();
			}

			if(mTarget != null)
			{
				//cpu has an alive target
				//move left if closest player is to the left
				float distance = mTarget.transform.position.x - this.gameObject.transform.position.x;
				if(distance < -1)
				{
					this.gameObject.transform.Translate(-MovementSpeed * Time.deltaTime, 0, 0);
				}
				//move right if closest player is to the right
				else if(distance > 1)
				{
					this.gameObject.transform.Translate(MovementSpeed * Time.deltaTime, 0, 0);
				}

				Vector3 targetPosition = mTarget.transform.position;
				targetPosition.x += UnityEngine.Random.Range (-1 * MissDistance, MissDistance);
				targetPosition.y += UnityEngine.Random.Range (-1 * MissDistance, MissDistance);
				LeftJoystickDirection = (targetPosition - this.gameObject.transform.position).normalized;
				if(mShouldThrow)
				{
					ThrowWeapon();
					mShouldThrow = false;
				}
			}
		}

		/**
		 * \brief finds the closest target to the computer 
		 */
		private Player GetNewTarget()
		{			
			Player closestPlayer = null;
			float closestDistance = 9999.9f;
			Player[] players = GameObject.FindObjectsOfType<Player>();
			if(players != null)
			{
				foreach(Player player in players)
				{
					if(!player.Dead)
					{
						//get closest player
						float distance = (player.gameObject.transform.position - this.gameObject.transform.position).magnitude;
						if(distance < closestDistance && player != this)
						{
							closestPlayer = player;
							closestDistance = distance;
						}
					}
				}
			}
			return closestPlayer;
		}

		private bool mShouldThrow = false;
		private PlayerBase mTarget;
	}
}

